package ezi

class CrawlerService {

  static expose = ['flex-remoting']
  static scope = 'session'
  Crawler crawler

  def searchByURL(String url, SearchType method, Integer threads = 5, Integer time = 10000, Integer depth = 2) {

    if (crawler?.threads) crawler.threads*.interrupt()
    if (crawler?.main) crawler?.main.interrupt()

    if (method == SearchType.BFS) {

      crawler = new Crawler(startThread: threads, maxDepth: depth, time: time)
      crawler.breadthFirstSearch(new Link(null, url, 0))

    } else {

      crawler = new Crawler(startThread: threads, maxDepth: depth, time: time)
      crawler.depthFirstSearch(new Link(null, url, 0));

    }

    crawler.main.join()
    return crawler.links.size() > 100 ? crawler.links[0..100] : crawler.links
  }

  File getCrawlerFile() {
    crawler.threads = null
    crawler.main = null
    //String name = new StringBuilder().append("crawler_").append(new Date().getTime() + "_").append(UUID.randomUUID()).append(".").append("crw").toString()
    File f = new File("crawler.craw")
    f.withObjectOutputStream { oos ->
      oos.writeObject(crawler)
    }
  }

  def loadCrawlerFile() {
    Crawler c
    new File("crawler.craw").withObjectInputStream(getClass().classLoader) { ois ->
      c = ois.readObject()
    }
    return c.links.size()  > 100 ? c.links[0..100] : c.links
  }

  def getMsg() {
    println "helllloooo"
    return "Hello world Lukasz&Michal";
  }

  public ArrayList<Integer> lista() {
    def lista = new ArrayList<Integer>();

    lista.add(1);
    lista.add(2);
    return lista;
  }

  public ArrayList<Link> links() {
    def links = new ArrayList<Link>();

    def link1 = new Link(null, "1", 0);
    def link2 = new Link(link1, "2", 1)
    def link3 = new Link(link2, "3", 1);

    links.add(link1);
    links.add(link2);
    links.add(link3);
    return links;
  }
}
